/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: MatrixToImageWriter
 * Author:   Administrator
 * Date:     2020/3/9 13:10
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.h3bpm.web.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author Administrator
 * @create 2020/3/9
 * @since 1.0.0
 */
public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);


        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }



//    public static void main(String[] args) throws IOException {
//        System.out.println("开始生成...");
//        byte[] jpgs = getMatrixByte("http://baidu.com", "jpg");
//
//        FileOutputStream fileOutputStream = new FileOutputStream("D:/test/2wm.jpg");
//
//        fileOutputStream.write(jpgs);
//
//
//        System.out.println("生成完毕！");
//
//    }

    /**
     * 获得 二维码的二进制
     * @param toUrl
     * @param imageType
     * @return
     * @throws Exception
     */
    public static byte[] getMatrixByte(String toUrl, String imageType)  {
        byte []  bytes = null;
        ByteArrayOutputStream bs = null;
        ImageOutputStream imOut = null;
        try {
            if (imageType == null) {
                imageType = "png";// 图片类型
            }

            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = multiFormatWriter.encode(toUrl, BarcodeFormat.QR_CODE, 400, 400, hints);

            bitMatrix = deleteWhite(bitMatrix);

            BufferedImage bufferedImage = toBufferedImage(bitMatrix);


            bs = new ByteArrayOutputStream();
            imOut = ImageIO.createImageOutputStream(bs);

            ImageIO.write(bufferedImage, imageType, imOut);

            bytes = bs.toByteArray();

        }catch (Exception e){


        }finally {
            if (imOut != null) {
                try {
                    imOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bs != null) {
                try {
                    bs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return  bytes;

    }

    /**
     * 删除白边
     * */

    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    private static void code() {
        try {
            String content = "127.0.0.1/api/contract/getSignatureWork?instanceId=eea72167-a3ec-4205-ad1e-cb924e8bec26";
            String path = "D:/";// 二维码保存的路径
            String codeName = UUID.randomUUID().toString();// 二维码的图片名
            String imageType = "jpg";// 图片类型
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
            File file1 = new File(path, codeName + "." + imageType);

            MatrixToImageWriter.writeToFile(bitMatrix, imageType, file1);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}